package com.company.management.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.company.management.config.CustomConfig;
import com.company.management.controller.report.rep.APIResult;
import com.company.management.controller.report.vo.UserDepRespVO;
import com.company.management.controller.report.vo.UserDepVO;
import com.company.management.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import com.company.management.dto.UploadParams;
import com.company.management.dto.UserDto;
import com.company.management.mapper.UserMapper;
import com.company.management.modal.entity.User;
import com.company.management.request.LoginRequest;
import com.company.management.service.UserService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
//import sun.misc.BASE64Decoder;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.*;


@Api(tags = "用户模块", value = "用户 UserController")
@RestController
@RequestMapping("api/users")
@Slf4j
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private CustomConfig config;

    @Value("${server.port}")
    private Integer port;

    @Resource
    private UserMapper userMapper;
    @Autowired
    private CustomConfig customConfig;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @ApiOperation("注册用户")
    @PostMapping("/register")
    public JsonData register(@RequestBody User user) {
        log.info("register user:{}", user);
        if (StringUtils.isNotEmpty(user.getUserName())
                && StringUtils.isNotEmpty(user.getPassword())) {
            if (userService.findUserByUserName(user.getUserName()) != null) {
                return JsonData.buildError("该用户已存在");
            }
            if (user.getPassword().length() <= 5) {
                return JsonData.buildError("密码长度大于5位");
            }
//            if(StringUtils.isEmpty(user.getAvatar()))
//                user.setAvatar(CommonUtils.getRamdomHeadImg());
            user.setScore(100); //默认100分
            user.setIsAdmin(0); //非管理员
            user.setEmpStatus(0); //在职
            user.setCreateDateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            log.info("register user:{}", user);
            int ret = userService.save(user);
            return ret == 1 ? JsonData.buildSuccess() : JsonData.buildError("注册失败");
        }
        return JsonData.buildWithData(ResultCode.REGISTER_FAILURE, null);
    }

    @ApiOperation("更新用户")
    @PostMapping("/updateUser")
    public JsonData updateUser(@RequestBody User user) {
        if (ObjectUtils.isNotEmpty(user.getUserId())) {
            if (StringUtils.isEmpty(user.getAvatar())) {
                user.setAvatar(CommonUtils.getRamdomHeadImg());
            }
            log.info("update user:{}", user);
            user.setUpdateTime(LocalDateTime.now());
            int ret = userService.update(user);
            return JsonData.buildSuccess(userService.findUserById(user.getUserId()));
        }
        return JsonData.buildWithData(ResultCode.REGISTER_FAILURE, null);
    }

    @ApiOperation("获取用户")
    @PostMapping("/userDetails/{userId}")
    public JsonData userDetails(@PathVariable Integer userId) {
        if (ObjectUtils.isNotEmpty(userId)) {
            UserDto userdto = userService.findUserById(userId);
            return JsonData.buildWithData(ResultCode.UPDATE_SUCCESS, userdto);
        }
        return JsonData.buildWithData(ResultCode.UPDATE_FAILURE, null);
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public JsonData login(@RequestBody LoginRequest loginRequest) {
        log.info("loginRequest:{}", loginRequest);
        if (StringUtils.isNotEmpty(loginRequest.getUserName())
                && StringUtils.isNotEmpty(loginRequest.getPwd())) {
            //String password = CommonUtils.MD5(loginRequest.getPwd());
            String password = loginRequest.getPwd();
            UserDto userDto = userService.findUserByUserNameAndPwd(loginRequest.getUserName(), password);
            if (ObjectUtils.isNotEmpty(userDto)) {
                String token = JWTUtils.geneJsonWebToken(userDto);
                log.info("token:{}", token);
                if (StringUtils.isNotEmpty(token)) {
                    Map<String, Object> map = new HashMap<>();

                    User user = new User();
                    user.setUserId(userDto.getUserId());
                    user.setToken(token);
                    user.setTokenUpdateTime(LocalDateTime.now());
                    user.setUpdateTime(LocalDateTime.now());
                    userService.update(user);
                    userDto = userService.findUserById(user.getUserId());
                    map.put("user", userDto);
                    return JsonData.buildWithData(ResultCode.LOGIN_SUCCESS, map);
                }
            }
        }
        return JsonData.buildError("用户名或密码错误");
    }

    @ApiOperation("用户登录")
    @PostMapping("/logout/{token}")
    public JsonData logout(@PathVariable String token) {
        //拿不到用户的数据，去掉这种方式获取用户
        UserDto userDto = userService.findUserByToken(token);

        if (userDto != null && userDto.getToken().equals(token)) {
            User user = new User();
            user.setUserId(userDto.getUserId());
            userMapper.logout(user);
            return JsonData.buildSuccess();
        } else {
            // 退出异常
            return JsonData.buildError(ResultCode.LOGOUT_FAILURE.msg);
        }
    }

    /**
     * 根据用户id查询用户信息
     *
     * @param request
     * @return
     */
    @ApiOperation("通过token查找用户信息")
    @GetMapping("findByToken")
    public JsonData findUserInfoByToken(HttpServletRequest request) {
        Integer userId = (Integer) request.getAttribute("user_id");
        if (ObjectUtils.isNotEmpty((userId))) {
            UserDto user = userService.findUserById(userId);
            if (user != null) {
                return JsonData.buildWithData(ResultCode.QUERY_SUCCESS, user);
            }
        }
        return JsonData.buildWithData(ResultCode.QUERY_FAILURE, null);
    }

    /**
     * @param userId
     * @return
     */
    @PostMapping("queryAvatar/{filename}")
    @ApiOperation("用户图片url")
    public JsonData queryAvatar(@PathVariable("userId") Integer userId) {
         UserDto userDto = userService.findUserById(userId);
        if (ObjectUtils.isNotEmpty(userId) && ObjectUtils.isNotEmpty(userDto)) {
            String url = userDto.getAvatar();
            return JsonData.buildSuccess(url);
        }
        return JsonData.buildError("用户id不能为空");
    }

    @PostMapping("/saveAvatar")
    @ApiOperation("保存头像")
    public JsonData saveAvatar(@RequestBody UploadParams uploadParams) {

        log.info("保存头像: {}", uploadParams);

        String file = uploadParams.getFile();
        String dataPrix = ""; // base64格式前头
        String data = ""; // 实体部分数据
        Integer userId = uploadParams.getUserId();
        if (StringUtils.isBlank(file) || ObjectUtils.isEmpty(userId)) {
            return JsonData.buildWithData(ResultCode.FAILURE, "上传失败，上传图片数据为空");
        } else {
            String[] d = file.split("base64,");//将字符串分成数组
            if (d != null && d.length == 2) {
                dataPrix = d[0];
                data = d[1];
            } else {
                return JsonData.buildWithData(ResultCode.FAILURE, "上传失败，数据不合法");
            }
        }

        String suffix = ""; // 图片后缀，用以识别哪种格式数据
        if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {
            // 编码的jpeg图片数据
            suffix = ".jpg";
        } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {
            // 编码的icon图片数据
            suffix = ".ico";
        } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {
            // 编码的gif图片数据
            suffix = ".gif";
        } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {
            // 编码的png图片数据
            suffix = ".png";
        } else {
            return JsonData.buildWithData(ResultCode.FAILURE, "上传失败，数据不合法");
        }

        String fileVerifyFolder = config.getAvartar_folder();

        FileUtil.mkdir(fileVerifyFolder);
        String uuid =  UUID.randomUUID().toString();
//        String fileName          = DateUtil.format(new DateTime(), "yyyy_MM_dd_HH_mm_ss_SSS");
        String fileNameAndSuffix =  uuid + suffix;

        String targetFileAbsolutePath = fileVerifyFolder + fileNameAndSuffix;


        //BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            // byte[] b = Base64.getDecoder().decode(data);
            //byte[] b = decoder.decodeBuffer(data);
            byte[] b = Base64.getDecoder().decode(data);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    // 调整异常数据
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(targetFileAbsolutePath);
            out.write(b);
            out.flush();
            out.close();
            String url = StrUtil.format("{}/api/users/showAvatar/{}", config.getBaseurl(), fileNameAndSuffix);
            Map<String, Object> map = new HashMap<>();
            map.put("url", url);
            User user = new User();
            user.setUserId(userId);
            user.setAvatar(url);
            userService.update(user);
            return JsonData.buildWithData(ResultCode.SUCCESS, map);
        } catch (IOException e) {
            log.error("系统异常，上传图片失败,msg={}", e.getMessage());

            return JsonData.buildWithData(ResultCode.FAILURE, "系统异常，上传图片失败");
        }

    }


    /**
     * 头像读取
     *
     * @param fileName
     * @param response
     */
    @ApiOperation("头像读取返回")
    @GetMapping("showAvatar/{fileName}")
    public void showAvatar(@PathVariable("fileName") String fileName, HttpServletResponse response) {

        ServletOutputStream outputStream;
        if (ObjectUtils.isNotEmpty(fileName)) {
            String filePath = customConfig.getAvartar_folder()+fileName;
            log.info("图像路径：{}", filePath);
            try {
                byte[] bytes = FileUtil.readBytes(filePath);

                outputStream = response.getOutputStream();
                response.setContentType("image/jpeg");
                outputStream.write(bytes);
            } catch (cn.hutool.core.io.IORuntimeException ior) {

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 头像读取
     *
     * @param score
     */
    @ApiOperation("设置分数，仅供测试")
    @PostMapping("setScore/{score}")
    public void setScore(@PathVariable Integer score) {
        if (ObjectUtils.isNotEmpty(score)) {
            List<UserDto> userDtoList = userService.listAll();
            if (CollectionUtils.isNotEmpty(userDtoList)) {
                List<User> usrList = new ArrayList<>();
                userDtoList.forEach(userDto -> {
                    User user = new User();
                    userDto.setScore(score);
                    BeanUtils.copyProperties(userDto, user);
                    usrList.add(user);
                });
                userService.batchUpdateUsers(usrList);
            }
        }
    }


    /**
     * Anis
     *
     * @return
     */
    @ApiOperation("返回用户部门树")
    @GetMapping("/user/tree")
    public APIResult getUserTree(@RequestParam("userId") Long userId) {
        //这里需要排除掉自己
        List<UserDepVO> userDepVOS = userMapper.selectUserDep(userId);
        List<UserDepRespVO> respVOS = buildTree(userDepVOS);
        return APIResult.ok(respVOS);
    }

    public static List<UserDepRespVO> buildTree(List<UserDepVO> data) {
        Map<Integer, UserDepRespVO> departmentMap = new HashMap<>();
        List<UserDepRespVO> result = new ArrayList<>();

        for (UserDepVO entry : data) {
            // 检查部门是否已存在
            UserDepRespVO departmentNode = departmentMap.get(entry.getDeptId());
            if (departmentNode == null) {
                // 如果部门不存在，则创建部门节点
                departmentNode = new UserDepRespVO(entry.getDeptId(), entry.getDeptName());
                departmentMap.put(entry.getDeptId(), departmentNode);
                result.add(departmentNode);
            }

            // 添加用户到部门的 children
            if (departmentNode.getChildren() == null) {
                departmentNode.setChildren(new ArrayList<>());
            }
            departmentNode.getChildren().add(new UserDepRespVO(entry.getUserId(), entry.getUserName()));
        }

        return result;
    }

}
